Copy list with random pointer

Time: O(N); Space: O(1); medium

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.

The Linked List is represented in the input/output as a list of n nodes. Each node is represented as a pair of [val, random_index] where:

  • val: an integer representing Node.val

  • random_index: the index of the node (range from 0 to n-1) where random pointer points to, or null if it does not point to any node.

Example 1:

Input: head = {RandomListNode} [[7,None],[13,0],[11,4],[10,2],[1,0]]

Output: {RandomListNode} [[7,None],[13,0],[11,4],[10,2],[1,0]]

Example 2:

Input: head = {RandomListNode} [[1,1],[2,1]]

Output: {RandomListNode} [[1,1],[2,1]]

Example 3:

Input: head = {RandomListNode} [[3,None],[3,0],[3,None]]

Output: {RandomListNode} [[3,None],[3,0],[3,None]]

Example 4:

Input: head = {RandomListNode} []

Output: {RandomListNode} []

Explanation:

  • Given linked list is empty (null pointer), so return null.

Constraints:

  • -10000 <= Node.val <= 10000

  • Node.random is null or pointing to a node in the linked list.

  • Number of Nodes will not exceed 1000.

Hints:

  1. Just iterate the linked list and create copies of the nodes on the go. Since a node can be referenced from multiple nodes due to the random pointers, make sure you are not making multiple copies of the same node.

  2. You may want to use extra space to keep old node —> new node mapping to prevent creating multiples copies of same node.

  3. We can avoid using extra space for old node —> new node mapping, by tweaking the original linked list. Simply interweave the nodes of the old and copied list. For e.g.

    • Old List: A –> B –> C –> D

    • InterWeaved List: A –> A’ –> B –> B’ –> C –> C’ –> D –> D’

  4. The interweaving is done using next pointers and we can make use of interweaved structure to get the correct reference nodes for random pointers.

[45]:
class RandomListNode(object):
    def __init__(self, x):
        self.label = x
        self.next = None
        self.random = None

1.

[46]:
class Solution1(object):
    """
    Time: O(N)
    Space: O(1)
    """
    def copyRandomList(self, head):
        """
        :type head: RandomListNode
        :rtype: RandomListNode
        """
        # copy and combine copied list with original list
        current = head
        while current:
            copied = RandomListNode(current.label)
            copied.next = current.next
            current.next = copied
            current = copied.next

        # update random node in copied list
        current = head
        while current:
            if current.random:
                current.next.random = current.random.next
            current = current.next.next

        # split copied list from combined one
        dummy = RandomListNode(0)
        copied_current, current = dummy, head
        while current:
            copied_current.next = current.next
            current.next = current.next.next
            copied_current, current = copied_current.next, current.next

        return dummy.next
[47]:
s = Solution1()

# [[7,null],[13,0],[11,4],[10,2],[1,0]]
head = RandomListNode(7)                       # idx = 0
head.next = RandomListNode(13)                 # idx = 1
head.next.next = RandomListNode(11)            # idx = 2
head.next.next.next = RandomListNode(10)       # idx = 3
head.next.next.next.next = RandomListNode(1)   # idx = 4

head.random = None                               # -> None
head.next.random = head                          # 13 -> 0
head.next.next.random = head.next.next.next.next # 11 -> 4
head.next.next.next.random = head.next.next      # 10 -> 2
head.next.next.next.next.random = head           # 1 -> 0

res = s.copyRandomList(head)
res_pointers = ['7 -> None','13 -> 7','11 -> 1','10 -> 11','1 -> 7']
for i in range(len(res_pointers)):
    if res.random:
        # print("Random Pointer: " + str(res.label) + " -> " + str(res.random.label))
        assert str(res.label) + " -> " + str(res.random.label) == res_pointers[i]
    else:
        # print("Random Pointer: " + str(res.label) + " -> None")
        assert str(res.label) + " -> None" == res_pointers[i]
    res = res.next

2.

[49]:
class Solution2(object):
    def copyRandomList(self, head):
        """
        :type head: RandomListNode
        :rtype: RandomListNode
        """
        dummy = RandomListNode(0)
        current, prev, copies = head, dummy, {}

        while current:
            copied = RandomListNode(current.label)
            copies[current] = copied
            prev.next = copied
            prev, current = prev.next, current.next

        current = head
        while current:
            if current.random:
                copies[current].random = copies[current.random]
            current = current.next

        return dummy.next
[50]:
s = Solution2()

head = RandomListNode(7)                       # idx = 0
head.next = RandomListNode(13)                 # idx = 1
head.next.next = RandomListNode(11)            # idx = 2
head.next.next.next = RandomListNode(10)       # idx = 3
head.next.next.next.next = RandomListNode(1)   # idx = 4

head.random = None                               # -> None
head.next.random = head                          # 13 -> 0
head.next.next.random = head.next.next.next.next # 11 -> 4
head.next.next.next.random = head.next.next      # 10 -> 2
head.next.next.next.next.random = head           # 1 -> 0

res = s.copyRandomList(head)
res_pointers = ['7 -> None','13 -> 7','11 -> 1','10 -> 11','1 -> 7']
for i in range(len(res_pointers)):
    if res.random:
        assert str(res.label) + " -> " + str(res.random.label) == res_pointers[i]
    else:
        assert str(res.label) + " -> None" == res_pointers[i]
    res = res.next

3.

[52]:
from collections import defaultdict

class Solution3(object):
    """
    Time: O(N)
    Space: O(N)
    """
    def copyRandomList(self, head):
        """
        :type head: RandomListNode
        :rtype: RandomListNode
        """
        clone = defaultdict(lambda: RandomListNode(0))
        clone[None] = None
        cur = head

        while cur:
            clone[cur].label = cur.label
            clone[cur].next = clone[cur.next]
            clone[cur].random = clone[cur.random]
            cur = cur.next

        return clone[head]
[53]:
s = Solution3()

head = RandomListNode(7)                       # idx = 0
head.next = RandomListNode(13)                 # idx = 1
head.next.next = RandomListNode(11)            # idx = 2
head.next.next.next = RandomListNode(10)       # idx = 3
head.next.next.next.next = RandomListNode(1)   # idx = 4

head.random = None                               # -> None
head.next.random = head                          # 13 -> 0
head.next.next.random = head.next.next.next.next # 11 -> 4
head.next.next.next.random = head.next.next      # 10 -> 2
head.next.next.next.next.random = head           # 1 -> 0

res = s.copyRandomList(head)
res_pointers = ['7 -> None','13 -> 7','11 -> 1','10 -> 11','1 -> 7']
for i in range(len(res_pointers)):
    if res.random:
        assert str(res.label) + " -> " + str(res.random.label) == res_pointers[i]
    else:
        assert str(res.label) + " -> None" == res_pointers[i]
    res = res.next